package com.hxgis.oc.ncep.base;

import com.hxgis.oc.product.file.DownloadTask;
import com.hxgis.oc.product.png.PngConvTask;
import com.hxgis.oc.util.PNGConvert;
import com.hxgis.oc.util.netcdf.NetcdfBuffer;
import com.hxgis.oc.util.w3d.base.W3dConvertMeta;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public abstract class NcepBase {

    public DownloadTask createATask(long fid, File outputFile) {
        String ds = getDataSet();
        DownloadTask task = new DownloadTask(fid, ds, outputFile);
        task.setUrl(this.generateUrl(fid));
        PngConvTask convTask = new PngConvTask(fid, ds, outputFile);
        task.addConvertTask(convTask);
        convTask.setConvFunc(this::convert2PngFile);
        return task;
    }

    public String generateOutputFileName(long fid)
    {
        return NcepUrlGenerator.generateRawFileName(requestLevelParam,String.valueOf(fid),"",requestVarParam);
    }

    public String getDataSet(){
        return dataSet;
    }

    protected String dataSet;
    protected String requestLevelParam;
    protected String requestVarParam;

    protected List<String> gribVarName = new ArrayList<>();

    protected W3dConvertMeta w3dMeta = new W3dConvertMeta();

    public String generateUrl(long fid)
    {
        String fidStr = String.valueOf(fid);
        return NcepUrlGenerator.generateUrl(requestLevelParam,fidStr.substring(0,8),fidStr.substring(8,10),requestVarParam);
    }

    public PNGConvert convert2PngFile(File ncFile){
        NetcdfBuffer ncBuffer = new NetcdfBuffer();
        if (ncBuffer.read(ncFile.getAbsolutePath(), gribVarName.toArray(new String[0]))) {
            int width = ncBuffer.getWidth();
            int height = ncBuffer.getHeight();
            List<float[]> bufferList = ncBuffer.getFloatBufferList();
            float[] values1 = bufferList.get(0);
            float[] values2 = bufferList.size() > 1 ? bufferList.get(1) : null;
            PNGConvert convert = new PNGConvert(width,height,values1,values2);
            convert.setClampMin(w3dMeta.getClampMin());
            convert.setClampMax(w3dMeta.getClampMax());
            convert.setFixValue(w3dMeta.getFixValue());
            return convert;
        }

        return null;
    }
}
